<script setup lang="js">
import { ref,onMounted } from 'vue'
import {Tickets} from "@element-plus/icons-vue";
import {
  fetchReturnReasonList,
  deleteReason,
  updateReasonStatus,
  addReason,
  getReasonDetail,
  updateReason,
} from "@/api/returnReason.js";
import {ElMessage} from "element-plus";

const defaultListQuery = {
  pageNum: 1,
  pageSize: 10,
};
const defaultReturnReason = {
  name:null,
  sort:0,
  status:1,
  createTime:null
};
const listQuery = Object.assign({}, defaultListQuery);

const returnReason = ref({
  name:null,
  sort:0,
  status:0,
  createTime:null
})
const returnReasonForm = ref(null)
const total = ref(0)

const reasonsData = ref([])
onMounted(() => {
  getReasonList()
})
// 获取列表数据
const getReasonList = async () => {
  const res = await fetchReturnReasonList(listQuery)
  reasonsData.value = res.data.data.list
  total.value = res.data.data.total
}

// 格式化订单创建时间
const formatDate = (date) => {
  // 检查是否为 Date 对象
  if (!(date instanceof Date)) {
    date = new Date(date);
  }
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hour = String(date.getHours()).padStart(2, '0');
  const minute = String(date.getMinutes()).padStart(2, '0');
  const second = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
}

// 切换状态
const handleStatusChange = (row) => {
 let ids = [];
 ids.push(row.id)
  let params = new URLSearchParams();
 params.append("ids", ids);
 params.append("status", row.status);
 updateReasonStatus(params).then(res => {
   ElMessage.warning(res.data.message);
   ElMessage.success("状态修改成功")
   getReasonList()
 })
}

// 删除
const handleDelete = (row) => {
  gotoDeleteReason(row.id);
};
const gotoDeleteReason = (ids) => {
  const params = new URLSearchParams({ ids });
  deleteReason(params).then(res => {
      ElMessage.success(`${res.data.message} 删除成功！`);
      getReasonList();
  }).catch(err => {
      ElMessage.error(`${err.data.message} 删除失败！`);
  });
};


// 页码改变
const handleCurrentChange = (currentPage) => {
  listQuery.pageNum = currentPage
  getReasonList()
}
// 页码大小改变
const handleSizeChange = (pageSize) => {
  listQuery.pageSize = pageSize
  listQuery.pageNum = 1
  getReasonList()
}

// 编辑弹窗
const operateReasonId = ref(null)
const titleText = ref('')
const editVisible = ref(false)
const handleAddReason = () => {
  editVisible.value = true
  operateReasonId.value = null
  titleText.value = '新增原因类型'
  returnReason.value = Object.assign({}, defaultListQuery)
}
const handleEditSubmit = () => {
  if (operateReasonId.value === null) {
    // 新增
    addReason(returnReason.value).then(res => {
      ElMessage.warning(res.data.message);
      ElMessage.success("添加成功")
      getReasonList()
      editVisible.value = false
    })
  } else {
    // 修改
    updateReason(operateReasonId.value, returnReason.value).then(res => {
      ElMessage.warning(res.data.message);
      ElMessage.success("修改成功")
      getReasonList()
      editVisible.value = false
    })
  }
}
const handleEdit = (row) => {
  editVisible.value = true
  titleText.value = '编辑原因类型'
  operateReasonId.value = row.id
  getReasonDetail(row.id).then(res => {
    console.log(res.data.data)
    returnReason.value = res.data.data
   returnReason.name = res.data.data.name
   returnReason.sort = res.data.data.sort
   returnReason.status = res.data.data.status
   returnReason.createTime = res.data.data.createTime
  })
}



</script>

<template>
  <div class="return-reason">
    <!--    添加商品按钮 -->
    <div class="add-reason">
      <div class="add-btn">
        <el-icon>
          <Tickets/>
        </el-icon>
        <span>数据列表</span>
      </div>
      <el-button type="primary" icon="plus" @click="handleAddReason" style="margin-left: 20px;">
        原因新增
      </el-button>
    </div>
    <!--      数据列表 -->
    <div class="data-list">
      <el-table :data="reasonsData" style="width: 100%;" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="100" align="center"></el-table-column>
        <el-table-column label="编号ID" align="center">
          <template #default="{row}">
            {{row.id}}
          </template>
        </el-table-column>
        <el-table-column label="原因类型" align="center">
          <template #default="{row}">
            {{row.name}}
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center">
          <template #default="{row}">
            {{row.sort}}
          </template>
        </el-table-column>
        <el-table-column label="是否可用" align="center">
          <template #default="{row}">
            <el-switch
                v-model="row.status"
                @change="handleStatusChange(row)"
                :active-value="1"
                :inactive-value="0">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" align="center">
          <template #default="{row}">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作"align="center">
          <template #default="{row}">
            <el-button type="primary" icon="edit" @click="handleEdit(row)">编辑</el-button>
            <el-popconfirm
                width="260"
                placement="bottom"
                confirm-button-text="确定"
                cancel-button-text="取消"
                title="是否确定删除该人气推荐商品？"
                @confirm="() => handleDelete(row)"
            >
              <template #reference>
                <el-button type="danger" icon="delete">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
            background
            layout="total, sizes,prev, pager, next,jumper"
            :total="total"
            :page-sizes="[5, 10, 20, 30]"
            v-model:page-size="listQuery.pageSize"
            v-model:current-page="listQuery.pageNum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>


  <!-- 编辑弹窗 -->
  <el-dialog
    :title="titleText"
    v-model="editVisible"
    width="30%"
  >
    <el-form :model="returnReason" ref="returnReasonForm" label-width="100px">
      <el-form-item label="原因类型：" prop="name">
        <el-input v-model="returnReason.name"></el-input>
      </el-form-item>
      <el-form-item label="原因排序：" prop="sort">
        <el-input v-model="returnReason.sort"></el-input>
      </el-form-item>
      <el-form-item label="是否可用：" >
        <el-switch
            v-model="returnReason.status"
            :active-value="1"
            :inactive-value="0">
        </el-switch>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleEditSubmit">保存</el-button>
        <el-button @click="editVisible = false">取消</el-button>
      </el-form-item>
    </el-form>

  </el-dialog>
</template>

<style scoped lang="scss">
.return-reason {
  margin-top: 20px;
  display: flex;
  flex-direction: column;

  .add-reason {
    //height: 30px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    margin-bottom: 20px;
    border: 1px solid #d5d5d5;
    border-radius: 5px;

    .add-btn {
      display: flex;
      align-items: center;

      span {
        margin-left: 8px;
        font-size: 18px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
  }
}
</style>